package com.zone.vehicle.superapp.datasource;

import android.content.Context;
import android.util.Log;

import com.saicmotor.pay.db.PayDaoUtilsStore;
import com.saicmotor.pay.db.entity.Pay;
import com.saicmotor.pay.entity.OrderEntity;
import com.saicmotor.pay.entity.PayDetail;
import com.saicmotor.pay.entity.PayEntity;
import com.saicmotor.pay.entity.PayResultEntity;
import com.saicmotor.pay.request.PayOrderRequestBody;
import com.saicmotor.pay.request.PayOrderRequestHeader;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.install.AndroidP;
import com.zone.lib.download.utils.DownloadUtil;
import com.zone.lib.download.utils.SharedPreferencesUtil;
import com.zone.sdk.common.http.base.PageResult;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.base.AppStoreResult;
import com.zone.sdk.module.appstore.base.StoreUtils;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.appstore.entity.AppListItemEntity;
import com.saicmotor.pay.entity.Goods;
import com.zone.sdk.module.appstore.entity.UserEntity;
import com.zone.sdk.module.appstore.request.AppsDetailRequest;
import com.saicmotor.pay.request.OrderSubmitRequest;
import com.saicmotor.pay.request.PayOrderRequest;
import com.saicmotor.pay.request.QueryPayResultRequest;
import com.zone.sdk.module.comment.base.CommentPage;
import com.zone.sdk.module.comment.entity.AppCommentScoreEntity;
import com.zone.sdk.module.comment.entity.CommentListEntity;
import com.zone.sdk.module.comment.entity.RecommendEntity;
import com.zone.sdk.module.comment.entity.RecommendListEntity;
import com.zone.sdk.module.comment.entity.SearchResultEntity;
import com.zone.sdk.module.comment.request.AppSearchRequest;
import com.zone.sdk.module.comment.request.CommentListRequest;
import com.zone.sdk.module.comment.request.CommentScoreRequest;
import com.zone.sdk.module.comment.request.RecommendListRequest;
import com.zone.sdk_api.ApiManager;
import com.zone.sdk_api.common.Content;
import com.zone.vehicle.sdk.module.superapp.request.AppListRequest;
import com.zone.vehicle.sdk.module.superapp.request.AppPushRequest;
import com.zone.vehicle.sdk.module.superapp.response.AppPushResponse;
import com.zone.vehicle.superapp.utils.TimeUtil;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;

import static com.zone.sdk_api.common.Content.USER_ID;
import static com.zone.sdk_api.common.Content.VIN;
import static com.zone.sdk_api.common.Content.VIN_TEST;

public class HomeDataSource {

    private static final String TAG = HomeDataSource.class.getSimpleName();

    public void indexSearch(String search, ResultCallBack<Result<CommentPage<SearchResultEntity>>> callback){
        AppSearchRequest request = new AppSearchRequest();
        request.setPageNum(0);
        request.setPageSize(10);
        request.setSearchName(search);
        request.setPageTime(TimeUtil.getNowTime());
        request.setSearchType(0);
        ApiManager.getInstance().indexSearch(request, callback);
    }

    public void getHomeAppListData(int pageNo, int pageSize, ResultCallBack<Result<AppStoreResult<AppListItemEntity>>> callBack){
        AppListRequest request = new AppListRequest();
        request.setPageNo(pageNo);
        request.setPageSize(pageSize);
        request.setShelvesState(com.zone.vehicle.sdk.module.superapp.entity.StoreUtils.HOME_PUT_ON);
        request.setHomeShow(com.zone.vehicle.sdk.module.superapp.entity.StoreUtils.HOME_SHOW);
        request.setOrderBy(new AppListRequest.OrderBy("c.sort", "desc"));
        ApiManager.getInstance().homeAppList(request, callBack);
    }

    public void getAppDetail(Context context, String code, ResultCallBack<Result<AppDetailEntity>> callBack){
        AppsDetailRequest request = new AppsDetailRequest();
        request.setSpuId(code);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appsDetail(request, callBack);
    }

    public void appList(List<String> codeList, ResultCallBack<Result<List<AppEntity>>> callBack){
        AppsDetailRequest request = new AppsDetailRequest();
        request.setCodeList(codeList);
        ApiManager.getInstance().appList(request, callBack);
    }

    public void submitOrder(Context context, String source, AppDetailEntity app, UserEntity user, ResultCallBack<Result<OrderEntity>> callback){
        OrderSubmitRequest request = new OrderSubmitRequest();
        request.setType(StoreUtils.ORDER_PAY);
        request.setUserId(user.getUserId());
        request.setSource(source);
        request.setDeviceType(StoreUtils.DEVICE_TYPE_VEHICLE);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        Goods goods = new Goods();
        goods.setGoodsCode("2");
        goods.setGoodsSkuCode(app.getCode());
        goods.setQuantity(1);
        goods.setGoodsSkuName(app.getName());
        float price = Float.parseFloat(app.getProductPrice());
        goods.setDiscountPrice(price);
        goods.setMarketPrice(price);
        goods.setPrice(price);
        List<Goods> goodsList = new LinkedList<>();
        goodsList.add(goods);
        request.setCartItems(goodsList);
        ApiManager.getInstance().submitOrder(request, callback);
    }

    public void payOrder(AppEntity app, UserEntity user, OrderEntity order, ResultCallBack<Result<PayEntity>> callback) {
        PayOrderRequest request = new PayOrderRequest();
        PayOrderRequestHeader header = new PayOrderRequestHeader();
        header.setAuthorization(user.getAccessToken());
        PayOrderRequestBody body = new PayOrderRequestBody();
        body.setMerchOrderId(order.getMerchOrderId());
        body.setGoodsDescription(app.getDescription());
        body.setPlatformMerchId(order.getPlatformMerchId());
        body.setOrderAmt(order.getOrderAmt());
        body.setTransAmt(order.getOrderAmt());
        body.setTimeExpire(TimeUtil.getTargetTime(1000 * 30 * 60));
        body.setPayScene(StoreUtils.PAY_SCENE);
        PayDetail detail = new PayDetail();
        detail.setProductCode("PAY_ZFB_NATIVE");
        ApiManager.getInstance().payOrder(request, callback);
    }

    public void queryPayResult(QueryPayResultRequest request, ResultCallBack<Result<PayResultEntity>> callback) {
        ApiManager.getInstance().queryPayResult(request, callback);
    }
    public void commentList(String code, ResultCallBack<Result<CommentListEntity>> callback){
        CommentListRequest request = new CommentListRequest();
        request.setObjectId(code);
        request.setPageNum(0);
        request.setPageSize(10);
        ApiManager.getInstance().commentCommentList(request, callback);
    }

    public void commentInitAmwayWallList(ResultCallBack<Result<RecommendListEntity>> callback){
        RecommendListRequest request = new RecommendListRequest();
        request.setPageNum(0);
        request.setPageSize(10);
        request.setPageTime(TimeUtil.getNowTime());
        ApiManager.getInstance().commentInitAmwayWallList(request, callback);
    }

    public void getRecommendListApp(int pageNo, int pageSize, ResultCallBack<Result<PageResult<RecommendEntity>>> callBack){
        RecommendListRequest baseRequest = new RecommendListRequest();
        ApiManager.getInstance().getRecommendListApp(baseRequest, callBack);
    }

    public void commentScore(String objectId, ResultCallBack<Result<AppCommentScoreEntity>> callback){
        CommentScoreRequest request = new CommentScoreRequest();
        request.setObjectId(objectId);
        ApiManager.getInstance().commentScore(request, callback);
    }

    public void downLoadApp(Context context, int status, AppDetailEntity appEntity){
        String userId = SharedPreferencesUtil.getInstance(context).getSP(Content.USER_ID);
        DownloadUtil.downLoad(context, status, userId, appEntity);
    }

    public void appletPush(Context context, AppDetailEntity appEntity, AppStatusEnum statusEnum, ResultCallBack<Result<AppPushResponse>> callback){
        AppPushRequest request = new AppPushRequest();
        request.setAppCode(appEntity.getCode());
        if (statusEnum == AppStatusEnum.DOWNLOAD_PREPARE
            || statusEnum == AppStatusEnum.INSTALL_PREPARE) {
            request.setActive("1");//下载
        }else if (statusEnum == AppStatusEnum.DOWNLOAD_PAUSE) {
            request.setActive("3");//下载
        }else if (statusEnum == AppStatusEnum.DOWNLOAD_CONTINUE) {
            request.setActive("4");//下载
        }else if (statusEnum == AppStatusEnum.UNINSTALLING_APP
            || statusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT
            || statusEnum == AppStatusEnum.LIGHT_DELETE){
            request.setActive("2");//卸载
        }
        String vin = SharedPreferencesUtil.getInstance(context).getSP(VIN);
        if (StringUtils.isEmpty(vin)){
            vin = VIN_TEST;
        }
        request.setVin(vin);
        request.setAppType(appEntity.getAppType());
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appPush(request, callback);
    }

    public void install(Context context, AppDetailEntity appEntity, AppStatusEnum statusEnum){
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
        if (ObjectUtils.isEmpty(download)){
            Log.d(TAG, "未找到下载信息");
            return;
        }
        if (statusEnum == AppStatusEnum.INSTALL_PREPARE && (
                download.getDownloadStatus() != AppStatusEnum.DOWNLOAD_COMPLETE.CODE
                        || download.getDownloadStatus() != AppStatusEnum.INSTALL_FAIL.CODE
        )){
            AndroidP.install28(context, download);
        }else if (statusEnum == AppStatusEnum.UNINSTALL_APP && download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE){
            AndroidP.uninstall(context, appEntity.getCode(), download.getPackageName());
        }
    }

    public List<Pay> listPay(){
        return PayDaoUtilsStore.getInstance().getPayAppDaoUtils().queryAll();
    }
}